<template>
  <dialog-box
    :isDialog="false"
    ref="myDialog"
    :showFooter="true"
    width="600px"
    @close="close"
    @sureHandle="sureHandle"
    :isFooterSlot="true"
    title="配置结构"
  >
    <template v-slot:dialogMain>
      <div>
        <div class="mb-10">
          <el-button type="primary" @click="addNode">新增</el-button>
          <span class="ml-20">请选择表字段拖入层级结构中</span>
        </div>
        <div class="mb-20">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-tree
                :data="dataSource"
                node-key="id"
                default-expand-all
                :expand-on-click-node="false"
                ref="treeIn"
              >
                <template #default="{ node, data }">
                  <el-input
                    v-model="data.label"
                    size="small"
                    v-if="data.edit"
                    @blur="data.edit = false"
                  ></el-input>
                  <span
                    :id="data.id"
                    @drop="drop_handler($event, node)"
                    @dragover="dragover_handler"
                    v-else
                    :data-level="node.level"
                    @dblclick="data.edit = true"
                  >
                    {{ node.label }}
                  </span>
                </template>
              </el-tree>
            </el-col>
            <el-col :span="12">
              <div>
                <el-tree
                  :data="dataSource2"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                  ref="treeOut"
                >
                  <template #default="{ node, data }">
                    <span
                      :id="data.id"
                      draggable="true"
                      @dragstart="handleNodeDragStart"
                      >{{ node.label }}</span
                    >
                  </template>
                </el-tree>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="form-box">
        <div>所属维度/度量</div>
        <el-select>
          <el-option
            v-for="(its, ix) in state.conditionList"
            :key="ix"
            :label="its.label"
            :value="its.value"
          />
        </el-select>
      </div>
    </template>
  </dialog-box>
</template>

<script setup lang="ts">
defineOptions({
  name: "ConfigStructure",
});
import dialogBox from "@/components/dialog-box/index.vue";
import { onMounted, computed, reactive, toRefs, ref } from "vue";
import {
  type ComponentSize,
  type FormInstance,
  type FormRules,
  ElMessage,
} from "element-plus";
const myDialog = ref(null);
const customDragImage = ref(null);
const moveData = ref();
const emit = defineEmits(["sureHandle"]);

const ruleForm = ref({
  name: "",
  comp: "",
  region: "",
  groupList: [],
});

let state = reactive({
  fieldList: [
    { label: "字段值1", value: 1 },
    { label: "字段值2", value: 2 },
    { label: "字段值3", value: 3 },
  ],
  conditionList: [
    {
      value: "1",
      label: "维度",
    },
    {
      value: "2",
      label: "度量",
    },
  ],
  measurementTree: [
    //维度
    {
      label: "节点1",
      id: "1",
      children: [
        {
          label: "节点1-1",
          id: "1-1",
        },
      ],
    },
    {
      label: "节点2",
      id: "2",
      children: [
        {
          label: "节点2-1",
          id: "2-1",
        },
        {
          label: "节点2-2",
          id: "2-2",
        },
      ],
    },
    {
      label: "节点3",
      id: "3",
      children: [
        {
          label: "节点3-1",
          id: "3-1",
        },
        {
          label: "节点3-2",
          id: "3-2",
        },
      ],
    },
  ],
});

interface Tree {
  id: number;
  label: string;
  children?: Tree[];
  flag?: "entity";
}

const treeIn = ref<InstanceType<typeof ElTree>>();
const treeOut = ref<InstanceType<typeof ElTree>>();

const dataSource = ref<Tree[]>([
  {
    id: 1,
    label: "蔬菜",
    edit: false,
    children: [
      {
        id: 9,
        edit: false,
        label: "辣椒",
      },
      {
        edit: false,
        id: 10,
        label: "丸子",
      },
    ],
  },
  {
    id: 2,
    label: "水果",
    edit: false,
    children: [
      {
        id: 5,
        edit: false,
        label: "软乎乎的",
      },
      {
        id: 6,
        edit: false,
        label: "刺刺的",
      },
    ],
  },
  {
    id: 3,
    label: "杂类",
    edit: false,
    children: [
      {
        id: 7,
        label: "红绿色",
        edit: false,
      },
      {
        id: 8,
        edit: false,
        label: "黑紫色",
      },
    ],
  },
]);

const dataSource2 = ref<Tree[]>([
  {
    id: 41,
    label: "香蕉",
  },
  {
    id: 42,
    label: "菠萝",
  },

  {
    id: 43,
    label: "榴莲（哈哈 我的最爱）",
  },
  {
    id: 44,
    label: "西红柿鸡蛋（不喜欢）",
  },
  {
    id: 45,
    label: "茄子",
  },
  {
    id: 46,
    label: "香菇",
  },
]);

const addNode = () => {
  dataSource.value.push({
    id: dataSource.value.length + 1,
    label: "",
    edit: true,
    children: [],
  });
};
const handleNodeDragStart = (ev) => {
  ev.dataTransfer.dropEffect = "copy";
  ev.dataTransfer.setData("text/plain", ev.target.id);
};

const dragover_handler = (ev) => {
  ev.preventDefault();
  ev.dataTransfer.dropEffect = "link";
};

const drop_handler = (ev, node) => {
  ev.preventDefault();
  let outId = ev.dataTransfer.getData("text/plain");
  let inId = ev.target.id;
  // 获取拖拽节点
  let outNode = treeOut.value.getNode(Number(outId));
  let parentId = node.parent.data.id;
  let nodeId = node.data.id;
  if (parentId) {
    setNodeData(parentId,outId,inId,outNode,ev)
  }else{
    setNodeData(nodeId,outId,inId,outNode,ev)
  }
};
const setNodeData = (id,outId,inId,outNode,ev) => {
  let arr = dataSource.value.find((item) => item.id == id).children;

  let reArr = arr.find((item) => item.id == outId);
  if (!reArr || reArr.length <= 0) {
    if (ev.target.dataset.level && ev.target.dataset.level == "2") {
      treeIn.value.insertAfter(outNode.data, Number(inId));
    } else {
      treeIn.value.append(outNode.data, Number(inId));
    }
  }
};
onMounted(() => {});

// 定义完成后，用defineExpose()暴露给父组件
const open = (data: any) => {
  // resetForm();
  // setDragDemo()
  if (data) {
    console.log(data, "111");
    // ruleForm.value = Object.assign({},{...data});
  }
  myDialog.value.handleOpen();
};
const close = () => {
  myDialog.value.handleClose();
};
const sureHandle = () => {
  // submitForm();
};
defineExpose({
  open,
  close,
});

const submitForm = async () => {
  if (!ruleFormRef) return;
  await ruleFormRef.value?.validate((valid, fields) => {
    if (valid) {
      console.log(Object.assign({}, { ...ruleForm.value }), "submit!");
      // console.log(toRefs(ruleForm), "submit!");
      ElMessage({
        type: "success",
        message: state.title + "成功!",
      });
      emit("sureHandle", Object.assign({}, { ...ruleForm.value }));
      close();
    }
  });
};

const resetForm = () => {
  if (!ruleFormRef) return;
  ruleFormRef.value?.resetFields();
};
</script>

<style lang="scss" scoped>
.ml-20 {
  margin-left: 20px;
}
.mb-10 {
  margin-bottom: 10px;
}
.mb-20 {
  margin-bottom: 2cap;
}
.form-box {
  display: flex;
  align-items: center;
  gap: 10px;
  > div {
    white-space: nowrap;
  }
}
</style>
